package com.ruoyi.common.config;

import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;

/**
 * @title: HttpClientConfig
 * @copyright: copyright (c) 2023
 * @author: jiangguanjun
 * @date: 2023/2/7 14:45
 * @firstReview:
 * @lastReview:
 * @desc:
 */

@Configuration
public class HttpClientConfig extends AbstractHttpClientConfig {
    @Bean(name = "poolProperties")
    @ConfigurationProperties(prefix = "http.pool")
    public HttpPoolProperties poolProperties() {
        return new HttpPoolProperties();
    }

    @Bean(value = "closeableHttpClient")
    public CloseableHttpClient closeableHttpClient(@Qualifier("poolProperties") HttpPoolProperties httpPoolProperties) {

        return this.buildHttpClient(httpPoolProperties);
    }

    @Bean(name = "httpRequestFactory")
    public ClientHttpRequestFactory httpRequestFactory(@Qualifier("closeableHttpClient") CloseableHttpClient httpClient) {
        HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
        httpRequestFactory.setConnectionRequestTimeout(10000);
        httpRequestFactory.setConnectTimeout(10000);
        httpRequestFactory.setReadTimeout(10000);
        return httpRequestFactory;
    }

    @Bean(name = "restTemplate")
    public RestTemplate restTemplate(@Qualifier("httpRequestFactory") ClientHttpRequestFactory clientHttpRequestFactory) {
        return this.buildRestTemplate(clientHttpRequestFactory, StandardCharsets.UTF_8);
    }
}
